using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Net;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Diagnostics;
// using ADODB;
// using System.IO;

using OneNote = Microsoft.Office.Interop.OneNote;

namespace Webber
{
    public partial class Form1 : Form
    {

        private XmlNodeList m_nsNotebooks;
        private XmlNodeList m_nsSections;
        private OneNote.Application m_oneApp;
       
        public Form1()
        {
            InitializeComponent();
            
            // Setup connection to onenote
            
        }

        ~Form1()
        {
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Activate();
            this.BringToFront();

            try
            {
                //System.Windows.Forms.MessageBox.Show("Created Ref");
                m_oneApp = new OneNote.Application();
            }
            catch (Exception f)
            {
                m_oneApp = null;
                System.Windows.Forms.MessageBox.Show("Cannot obtain reference to OneNote: " + f.Message);
            }

            // Get List of Notebooks
            if (m_oneApp != null)
            {
                m_nsNotebooks = ONXmlRequestor.GetNodes(m_oneApp, null, OneNote.HierarchyScope.hsNotebooks, "//one:Notebook");
            }

            
            // Put notebooks in combo box
            if (m_nsNotebooks != null)
            {

                // clear combo box
                cbxNotebooks.Items.Clear();
                
                // add name of each item
                XmlNode node;
                for (int i = 0; i < m_nsNotebooks.Count; i++)
                {
                    node = m_nsNotebooks.Item(i);
                    cbxNotebooks.Items.Add(node.Attributes["name"].Value);
                }
            }

            // initialize default logging path to desktop
            tbLogFile.Text = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\log.txt";
            

            this.BringToFront();
            this.Activate();
        }

        private void cbxNotebooks_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Enable scheduling option
            cbEnableSched.Enabled = true;

            // Enable save location path
            txtPath.Enabled = true;

            // Get selected notebook information
            XmlNode nodeNotebook = m_nsNotebooks.Item(cbxNotebooks.SelectedIndex);              
            string strNotebookPath = nodeNotebook.Attributes["path"].Value; // notebook path
            string strNotebookId = nodeNotebook.Attributes["ID"].Value;     // notebook id

            // Make sure path is followed by a / or \
            if (strNotebookPath.ToLower().StartsWith("http"))
            {
                if (!strNotebookPath.EndsWith("/"))
                {
                    strNotebookPath += '/';
                }
            }
            else
            {
                if (!strNotebookPath.EndsWith("\\"))
                {
                    strNotebookPath += '\\';
                }
            }

            // Update path location
            txtPath.Text = strNotebookPath + "webview.html";
            

            
            // Add sections of selected notebook to listbox
            m_nsSections = ONXmlRequestor.GetNodes(m_oneApp, strNotebookId, OneNote.HierarchyScope.hsSections, "//one:Section");
            if (m_nsSections != null)
            {
                /* no more combo box
                // cleack list box
                lbxSections.Items.Clear();
               
                // add name of each section
                XmlNode node;
                for (int i = 0; i < m_nsSections.Count; i++)
                {
                    node = m_nsSections.Item(i);
                    lbxSections.Items.Add(node.Attributes["name"].Value);
                    lbxSections.SetItemChecked(i,true);
                }
                */

                // enable export
                btnExport.Enabled = true;
            }
        }

        
        /*
        private string ParsePathString(string path)
        {
            string result = "";

            // check if location is a folder
            if (System.IO.Directory.Exists(path))
            {
                result = path;
            }

            // try to parse out the last part
            else
            {
                result = (System.IO.Directory.GetParent(path)).ToString();
            }
            return result;
        }
        */
               
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            /* No more section selection
            // get number of checked sections
            int numCheckedSections = 0;
            for (int i = 0; i < lbxSections.Items.Count; i++)
            {
                if (lbxSections.GetItemCheckState(i) == CheckState.Checked)
                {
                    numCheckedSections++;
                }
            }
            
            // create array of cehcked sections and populate it
            XmlNode[] pxnSections = new XmlNode[numCheckedSections];
            int curPos = 0;
            for (int i = 0; i < lbxSections.Items.Count && curPos < numCheckedSections; i++)
            {
                if (lbxSections.GetItemCheckState(i) == CheckState.Checked)
                {
                    pxnSections[curPos] = m_nsSections.Item(i);
                    curPos++;
                }
            }
            */

            // create array of cehcked sections and populate it
            XmlNode[] pxnSections = new XmlNode[m_nsSections.Count];
            for (int i = 0; i < m_nsSections.Count; i++)
            {
                pxnSections[i] = m_nsSections.Item(i);
            }

            // check export path
            bool pathOk = true;


            // check file extension
            if ((txtPath.Text.Trim().ToLower()).EndsWith(".htm") |
                (txtPath.Text.Trim().ToLower()).EndsWith(".html"))
            {
                // Everything OK
            }
            else
            {
                // add extension
                txtPath.Text += ".htm";
            }

            // check directory existence
            if (txtPath.Text.ToLower().Contains("http://") | txtPath.Text.ToLower().Contains("https://"))
            {
                // NO CHECK FOR HTTP://
                // TODO: add check for HTTP
            }
            else
            {
                System.IO.FileInfo fileInfo = new System.IO.FileInfo(txtPath.Text);

                if (!fileInfo.Directory.Exists)
                {
                    pathOk = false;
                    MessageBox.Show("Error: The notebook export path does not exist");
                }
            }

            // get application directory
            string strAppDirectory = (string)Registry.GetValue("HKEY_CURRENT_USER\\Software\\David Tse\\OneNote Webber", "AppPath", "");
            if (strAppDirectory == null)
            {
                pathOk = false;
                MessageBox.Show("Error: Cannot find required registry key. Please reinstall this application.");
            }
            else
            {
                if (!strAppDirectory.EndsWith("\\"))
                {
                    strAppDirectory += "\\";
                }
            }

            if (pathOk)
            {
                if (cbEnableSched.Checked)
                {
                    // schedule this export
                    
                    // get notebook name
                    string strNotebookName = m_nsNotebooks.Item(cbxNotebooks.SelectedIndex).Attributes["name"].Value;
                    string strTaskName = "Export Notebook - " + strNotebookName;

                    string command =
                        "/create /tn \"" + strTaskName + "\" " +
                        "/tr \"\\\"" + strAppDirectory + "cwebber.exe\\\" ";

                    // add command arguments
                    // Note:because of Vista bug with schtasks.exe
                    //      we need to do a cheap hack and surround the arguments with quotes and spaces

                    // form arugments for vista's tasksched.exe
                    // After some experimentation, i found surrounding the arguments with
                    // 1 " infront and 2 " at the end gave me the desired result
                    if (System.Environment.OSVersion.Version.Major >= 6)
                    {
                        command +=
                            "\\\" ";
                        
                        command +=
                            "\\\"" + strNotebookName + "\\\" " +
                            "\\\"" + txtPath.Text + "\\\" ";

                        if (cbLog.Checked)
                        {
                            command +=
                                "\\\"" + tbLogFile.Text + "\\\" ";
                        }

                        command += "\\\" \\\" ";
                    }
                    // form arugments for other versions of tasksched.exe
                    else
                    {
                        command +=
                            "\\\"" + strNotebookName + "\\\" " +
                            "\\\"" + txtPath.Text + "\\\" ";

                        // add option logging command
                        if (cbLog.Checked)
                        {
                            command +=
                                "\\\"" + tbLogFile.Text + "\\\"";
                        }
                    }


                    command +=
                            "\" " +
                        "/sc DAILY " +
                        "/st " + dateTimePicker1.Value.TimeOfDay.ToString();                  


                    // try to add the task
                    int iExitCode = -1;
                    String strErrMessage = "";
                    try
                    {
                        Process p = Process.Start("schtasks.exe",command);
                        p.WaitForExit();
                        iExitCode = p.ExitCode;
                    }
                    catch (Exception f)
                    {
                        strErrMessage = f.Message;
                    }


                    if (iExitCode == 0)
                    {
                        DialogResult dr = MessageBox.Show("Export task successfully scheduled as \"" + strTaskName + "\".\r\n\r\nRun task now?", strTaskName, MessageBoxButtons.YesNo);

                        if (dr == DialogResult.Yes)
                        {
                            // run rule now
                            Process.Start("schtasks.exe", "/run /tn \"" + strTaskName + "\""); 
                        }
                        if (dr == DialogResult.No)
                        {
                            // do nothing
                        }
                    }
                    else
                    {
                        MessageBox.Show("Failed to scheduled task \"" + strTaskName + "\" (Exit code " + iExitCode + ")." + strErrMessage + "\r\n\r\nCheck if the task already exists in the task scheduler.");
                    }                    
                }
                else
                {
                    // Export the notebook
                    Form2 exportDlg = new Form2(m_nsNotebooks.Item(cbxNotebooks.SelectedIndex), pxnSections, txtPath.Text);
                    this.Hide();
                    exportDlg.ShowDialog();
                }
            }
            
                
            
            this.Close();
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (m_oneApp != null)
            {
                //System.Windows.Forms.MessageBox.Show("Released Ref");
                m_oneApp = null;
                //Marshal.ReleaseComObject(m_oneApp);
            }
        }


        private void cbLog_CheckedChanged(object sender, EventArgs e)
        {
            tbLogFile.Enabled = cbLog.Checked;
            btnBrowseLog.Enabled = cbLog.Checked;
        }

        private void btnBrowseLog_Click(object sender, EventArgs e)
        {
            DialogResult result = saveFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                tbLogFile.Text = saveFileDialog1.FileName;
            }
        }

        private void cbEnableSched_CheckedChanged(object sender, EventArgs e)
        {
            groupSched.Enabled = cbEnableSched.Checked;
        }

        private void tgtSave_Click(object sender, EventArgs e)
        {
            DialogResult result = saveFileDialog2.ShowDialog();
            if (result == DialogResult.OK)
            {
                txtPath.Text = saveFileDialog2.FileName;
            }

        }
    }
}